package com.geo.geotool.entity.sql;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.geo.geotool.service.trans.GeometryFormatTrans;
import com.geo.geotool.service.trans.IGeometryFormatTrans;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.jdbc.SQL;


/**
 * • @Description: 要素查询实体
 * • @author  : yell
 * • @date : 2021/11/18  15:05
 */
@Data
public class QFeatureEntity implements IFeatureSQL {
    private String layerName;
    private String whereClause;
    private String attributes;
    private String needGeoJson = "0";
    private String srId = "4526";
    private GeoAnalyse geoAnalyse;
    @Override
    public String buildFeatureSQL() throws Exception{
        return new SQL(){
            {
                if(needGeoJson.equals("1")){
                    attributes = attributes + ",ST_AsGeoJSON(the_geom) as geometry";
                }
                SELECT(attributes);
                FROM(layerName);
                whereClause = StringUtils.isEmpty(whereClause)?
                        " ("+ geoAnalyse.getGeoAnalyseWhereClause(srId)+") ":
                        whereClause + (StringUtils.isEmpty(geoAnalyse.getGeoAnalyseWhereClause(srId))? "" : " and (" + geoAnalyse.getGeoAnalyseWhereClause(srId))+")";
                WHERE(whereClause);
            }
        }.toString();
    }

    @Data
    public static class GeoAnalyse{
        private String relation;
        private String theGeom;
        String getGeoAnalyseWhereClause(String srid) throws Exception {
            if(StringUtils.isEmpty(relation) || StringUtils.isEmpty(theGeom)){
                return "";
            }
            JSONObject jsonObject = JSONObject.parseObject(theGeom);
            JSONArray geoJSONS = jsonObject.getJSONArray("features");
            String geomWhere = "";
            IGeometryFormatTrans geometryFormatTrans = new GeometryFormatTrans();
            for(int  i = 0 ; i < geoJSONS.size() ; i++){
                JSONObject geomObj = geoJSONS.getJSONObject(i);
                JSONObject geometry = geomObj.getJSONObject("geometry");
                String geoJsonObJ = geometryFormatTrans.geoFormatTrans(geometry.toJSONString());
                String functionName = "";
                switch (relation){
                    case "intersects":
                        functionName = "st_intersects";
                        break;
                }
                if( i > 0 ){
                    geomWhere = geomWhere + " or " ;
                }
                geomWhere = geomWhere + functionName+"(the_geom,st_setsrid(st_GeomFromGeoJSON('"+geoJsonObJ+"'),"+srid+"))";

            }

            return geomWhere;
        }
    }
}
